package com.lframework.xingyun.basedata.impl.member;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lframework.starter.web.core.impl.BaseMpServiceImpl;
import com.lframework.starter.web.core.utils.PageResultUtil;
import com.lframework.starter.web.core.utils.OpLogUtil;
import com.lframework.starter.common.exceptions.impl.DefaultClientException;
import com.lframework.starter.web.core.annotations.oplog.OpLog;
import com.lframework.starter.web.inner.components.oplog.OtherOpLogType;
import com.lframework.starter.web.core.components.resp.PageResult;
import java.io.Serializable;
import com.lframework.starter.common.utils.ObjectUtil;
import com.lframework.starter.common.utils.Assert;
import com.lframework.xingyun.basedata.entity.Coupon;
import com.lframework.xingyun.basedata.entity.MemberCoupon;
import com.lframework.xingyun.basedata.mappers.MemberCouponMapper;
import com.lframework.xingyun.basedata.service.coupon.CouponService;
import com.lframework.xingyun.basedata.service.member.MemberCouponService;
import com.lframework.xingyun.basedata.service.member.MemberService;
import com.lframework.xingyun.basedata.vo.coupon.QueryCouponVo;
import com.lframework.xingyun.basedata.vo.member.*;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class MemberCouponServiceImpl extends BaseMpServiceImpl<MemberCouponMapper, MemberCoupon> implements MemberCouponService {

    @Override
    public PageResult<MemberCoupon> queryPage(Integer pageIndex, Integer pageSize, QueryMemberCouponVo vo) {

        Assert.greaterThanZero(pageIndex);
        Assert.greaterThanZero(pageSize);

        IPage<MemberCoupon> page = getBaseMapper().queryPage(vo);
        return PageResultUtil.convert(page);
    }

    @Override
    public List<MemberCoupon> queryList(QueryMemberCouponVo vo) {

        return getBaseMapper().queryList(vo);
    }

    @Cacheable(value = MemberCoupon.CACHE_NAME, key = "@cacheVariables.tenantId() + #id", unless = "#result == null")
    @Override
    public MemberCoupon findById(String id) {

        return getBaseMapper().selectById(id);
    }

    @OpLog(type = OtherOpLogType.class, name = "新增用户卡券关系表，ID：{}", params = {"#id"})
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String create(CreateMemberCouponVo vo) {

        MemberCoupon data = new MemberCoupon();
        data.setMemberId(vo.getMemberId());
        data.setCouponId(vo.getCouponId());
        data.setExpiryDate(vo.getExpiryDate());
        data.setCouponStatus(vo.getCouponStatus());
        data.setTotalValue(vo.getTotalValue());
        data.setAdded(vo.getAdded());
        data.setAllowValue(vo.getAllowValue());

        getBaseMapper().insert(data);

        OpLogUtil.setVariable("id", data.getId());
        OpLogUtil.setExtra(vo);

        return data.getId();
    }

    @OpLog(type = OtherOpLogType.class, name = "修改用户卡券关系表，ID：{}", params = {"#id"})
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(UpdateMemberCouponVo vo) {

        MemberCoupon data = getBaseMapper().selectById(vo.getId());
        if (ObjectUtil.isNull(data)) {
            throw new DefaultClientException("用户卡券关系表不存在！");
        }

        LambdaUpdateWrapper<MemberCoupon> updateWrapper = Wrappers.lambdaUpdate(MemberCoupon.class)
                .set(MemberCoupon::getMemberId, vo.getMemberId())
                .set(MemberCoupon::getCouponId, vo.getCouponId())
                .set(MemberCoupon::getExpiryDate, vo.getExpiryDate())
                .set(MemberCoupon::getCouponStatus, vo.getCouponStatus())
                .set(MemberCoupon::getTotalValue, vo.getTotalValue())
                .set(MemberCoupon::getAdded, vo.getAdded())
                .set(MemberCoupon::getAllowValue, vo.getAllowValue())
                .eq(MemberCoupon::getId, vo.getId());

        getBaseMapper().update(updateWrapper);

        OpLogUtil.setVariable("id", data.getId());
        OpLogUtil.setExtra(vo);
    }

    @OpLog(type = OtherOpLogType.class, name = "发放卡券，数量：{}", params = {"#num"})
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void couponGrant(CouponGrantVo vo) {
        List<String> memberIds = Optional.ofNullable(vo.getMemberId()).orElseGet(ArrayList::new);
        if (vo.getAllMember()) {
            memberIds.addAll(getThis(MemberService.class).selectByAvailable(true));
        }

        DateTime now = DateUtil.date();

        List<String> couponIds = vo.getCouponItem().stream()
                .map(CouponItemVo::getCouponId)
                .collect(Collectors.toList());

        Map<String, Coupon> couponMap = getThis(CouponService.class).getBaseMapper().selectByIds(couponIds).stream()
                .collect(Collectors.toMap(Coupon::getId, Function.identity()));

        List<MemberCoupon> list = new ArrayList<>();
        for (CouponItemVo couponItemVo : vo.getCouponItem()) {
            for (String memberId : memberIds) {
                String couponId = couponItemVo.getCouponId();
                MemberCoupon data = new MemberCoupon();
                data.setMemberId(memberId);
                data.setCouponId(couponId);
                Coupon coupon = couponMap.get(couponId);
                if (Objects.nonNull(coupon)) {
                    // 有效天数
                    Integer effectiveDay = coupon.getEffectiveDay();
                    data.setExpiryDate(now.offsetNew(DateField.DAY_OF_YEAR, effectiveDay).toLocalDateTime());
                    // 状态
                    data.setCouponStatus(1);
                    // 增值比例
                    data.setAdded(coupon.getAdded());
                    // 总值
                    BigDecimal added = coupon.getAdded().divide(BigDecimal.valueOf(100), RoundingMode.HALF_DOWN);
                    BigDecimal addedValue = coupon.getParValue().multiply(added);
                    data.setTotalValue(coupon.getParValue().add(addedValue));
                    // 可用值
                    data.setAllowValue(data.getTotalValue());
                }
                list.add(data);
            }
        }
        saveBatch(list);

        OpLogUtil.setVariable("num", list.size());
        OpLogUtil.setExtra(vo);
    }

    @CacheEvict(value = MemberCoupon.CACHE_NAME, key = "@cacheVariables.tenantId() + #key")
    @Override
    public void cleanCacheByKey(Serializable key) {

    }
}

